import requests


def call_execute_sql_api(sql, connection_info):
    """
    通过 requests 调用执行 SQL 的接口服务

    参数：
        sql: 要执行的 SQL 语句字符串
        connection_info: 数据库连接信息字典，例如：
            {
                "host": "localhost",
                "user": "your_username",
                "password": "your_password",
                "database": "your_database",
                "port": 3306  # 可选
            }

    返回：
        接口返回的结果数据（字典格式），如果请求失败则返回 None
    """
    url = "http://127.0.0.1:5000/execute_sql"

    # 构造请求体
    payload = {
        "sql": sql,
        "connection_info": connection_info
    }

    headers = {
        "Content-Type": "application/json"
    }

    try:
        response = requests.post(url, json=payload, headers=headers)
        if response.status_code == 200:
            try:
                return {"result": str(response.json()["result"])}
            except Exception as e:
                return {"result": f"解析响应 JSON 失败：{str(e)}"}
        else:
            return {"result": f"请求失败，状态码：{response.status_code}"}
    except Exception as e:
        return {"result": str(e)}


# 示例调用
if __name__ == "__main__":
    sql_query = "select * from test01 where id = 1"  # 替换为你的实际 SQL 语句
    conn_info = {
        "host": "localhost",
        "user": "user",
        "password": "Password",
        "database": "mydb",
        "port": 3136
    }

    result = call_execute_sql_api(sql_query, conn_info)
    print("接口返回结果：", result)
